// pages/article/read.js
let util = require('../../utils/util.js')
let recorderManager = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    article: {},
    recorderOptions: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id
    if (!id) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      return
    }
    util.httpAuthPost('/api/article/detail', { id: id }, res => {
      if (res.resultCode === 0) {
        this.setData({
          article: res.data
        })
      }
    })
    this.initRecorderManager()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  initRecorderManager: function() {

    recorderManager = wx.getRecorderManager()
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    recorderManager.onResume(() => {
      console.log('recorder resume')
    })
    recorderManager.onPause(() => {
      console.log('recorder pause')
    })
    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      const { tempFilePath } = res
      // const innerAudioContext = wx.createInnerAudioContext()
      // innerAudioContext.autoplay = true
      // innerAudioContext.src = res.tempFilePath
      // innerAudioContext.onPlay(() => {
      //   console.log('开始播放')
      // })
      // innerAudioContext.onError((res) => {
      //   console.log(res.errMsg)
      //   console.log(res.errCode)
      // })
      util.uploadFile(res.tempFilePath)
    })
    recorderManager.onFrameRecorded((res) => {
      const { frameBuffer } = res
      console.log('frameBuffer.byteLength', frameBuffer.byteLength)
    })
    const options = {
      duration: 10000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 24000 ,
      format: 'mp3',
      frameSize: 128
    }
    this.setData({
      recorderOptions: options
    })
    
  },
  onTouchStart: function(e) {
    recorderManager.start(this.data.recorderOptions)
  },
  onTouchEnd: function(e) {
    recorderManager.stop()
  }
})